package com.iknight.mgr.core.template;

import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Excel解析模板
 * @author JeryZym
 */
public class ExcelParseTemplate {
    private final static Logger logger = LogManager.getLogger(ExcelParseTemplate.class);

    /**
     * 获取导入模板
     *
     * @return
     */
    public static JSONObject getTgTemplate(Resource resource) {
        JSONObject template = new JSONObject();
        List<JSONObject> sheets = new ArrayList<>();
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(resource.getInputStream());
            Element rootElement = document.getRootElement();
            Iterator iterator = rootElement.elementIterator();

            while (iterator.hasNext()) {
                logger.info("开始进行模板文件遍历");
                JSONObject sheetJo = new JSONObject();
                Element sheet = (Element) iterator.next();
                sheetJo.put("index", sheet.attribute("index").getStringValue());

                JSONObject entityJo = new JSONObject();
                Element entity = sheet.element("entity");
                entityJo.put("entityName", entity.attribute("name").getStringValue());
                entityJo.put("tableName", entity.attribute("table").getStringValue());

                Element columns = entity.element("columns");
                Iterator<Element> column = columns.elementIterator();
                List<JSONObject> cols = new ArrayList<>();
                while (column.hasNext()) {
                    JSONObject col = new JSONObject();
                    Element colEl = column.next();
                    col.put("fieldName", colEl.attribute("name").getStringValue());
                    col.put("fieldType", colEl.attribute("type").getStringValue());
                    cols.add(col);
                }
                entityJo.put("columns", cols);
                sheetJo.put("entity", entityJo);
                sheets.add(sheetJo);
            }
        } catch (DocumentException exception) {
            exception.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        template.put("sheet", sheets);
        return template;
    }
}
